import com.alibaba.fastjson.JSON;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.io.Files;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by donar on 17/3/25.
 */
public class BuildSearchJSON {
    public static void main(String[] args) throws SQLException, IOException {
        getSearchJSON("USA");
        getSearchJSON("CANADA");
        getSearchJSON("MEXICO");
    }

    private static void getSearchJSON(String site) throws SQLException, IOException {
        Connection connection = JdbcUtil.getConnection();
        ResultSet rs = connection.createStatement().executeQuery(
                "select name ,id_path,name_path from amazon_catalog where has_children = 0 AND site ='"+site+"' "
        );
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        while(rs.next()){
            Map<String,String> map = new HashMap<String, String>();
            map.put("name",rs.getString("name"));
            map.put("idPath",rs.getString("id_path"));
            String namePath = rs.getString("name_path").replaceAll(", ","----");
            map.put("namePath", Joiner.on(" > ").join(namePath.split(",")).replaceAll("----",", "));
            list.add(map);
        }
        String usasearch = JSON.toJSONString(list);
        Files.write(usasearch,new File(site+".json"), Charsets.UTF_8);
    }
}
